import json

from django.core import serializers
from django.db import transaction
from django.http import HttpResponse, JsonResponse
from django.views import View
from books.models import Books


class BookListView(View):
    """ 直接继承 ListView 即可 """


    # 可选：自定义查询逻辑
    # 查询所有书籍列表
    def get(self, request):
        books = Books.objects.all()
        data = serializers.serialize('json', books)
        return JsonResponse(data, safe=False)


    def post(self, request):
        data = json.loads(request.body)
        key1 = data.get('username')
        key2 = data.get('password')


        try:
            print(key1, key2)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)



        with transaction.atomic():
            print(key1, key2)



        print(key1, key2)
        return JsonResponse(data, safe=False)